﻿using AutoMapper;
using MediatR;
using RedDragon.Common.Domain.AuthorizeRBAC;
using RedDragon.Common.Infrastructure.Interface;
using RedDragon.RBAC.API.Application.Common.WarehouseW;
using RedDragon.RBAC.ErrorCodeEnum;
using T.Common.Domain.Common;
using Yitter.IdGenerator;

namespace RedDragon.RBAC.API.Application.Common.Permission
{
    public class UpdatePermissionsHandler : IRequestHandler<UpdatePermissionsCommand, Result>
    {
        /// <summary>
        /// mapper
        /// </summary>
        private readonly IMapper mapper;
        /// <summary>
        /// 权限仓储
        /// </summary>
        public readonly IBaseRepository<Permissions> permissionsRepository;
        /// <summary>
        /// 日志
        /// </summary>
        private readonly ILogger<UpdatePermissionsHandler> logger;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="mapper"></param>
        /// <param name="permissionsRepository"></param>
        /// <param name="logger"></param>
        public UpdatePermissionsHandler(IMapper mapper, IBaseRepository<Permissions> permissionsRepository, ILogger<UpdatePermissionsHandler> logger)
        {
            this.mapper = mapper;
            this.permissionsRepository = permissionsRepository;
            this.logger = logger;
        }

        /// <summary>
        /// 权限修改
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Result> Handle(UpdatePermissionsCommand request, CancellationToken cancellationToken)
        {
            var result = new Result() { Code = (int)CommonErrorCode.Added };
            try
            {
                Permissions permissions = mapper.Map<Permissions>(request);
                //权限编号 雪花ID
                permissions.PermissionCoding = YitIdHelper.NextId().ToString();
                var res = await permissionsRepository.Update(permissions);
                if (res > 0)
                {
                    result.Code = (int)CommonErrorCode.Success;
                    result.Msg = "权限修改成功";
                }
            }
            catch (Exception ex)
            {
                result.Msg = "权限修改失败" + ex.Message;
                logger.LogError("权限修改失败" + ex.Message);
            }
            return result;
        }
    }
}
